package com.sys.quartz;

import com.bhudy.base.QueryFilter;
import com.bhudy.enums.Relation;
import com.sys.entity.SysCrontab;
import com.sys.entity.SysMessage;
import com.sys.entity.SysMessageRecord;
import com.sys.service.SysMessageRecordService;
import com.sys.service.SysMessageService;
import com.sys.utils.Utils;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * Created by Administrator on 2019/11/4/004.
 */
@Component
@PersistJobDataAfterExecution
public class SysMessageQuartz implements Job {
    @Autowired
    private SysMessageService sysMessageService;
    @Autowired
    private SysMessageRecordService sysMessageRecordService;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        JobDataMap jobDataMap = jobExecutionContext.getTrigger().getJobDataMap();
        Long sysCrontabId = jobDataMap.getLong(SysCrontab.CRONTAB_ID);
        QueryFilter queryFilter = new QueryFilter();

        // 获取未送达用户
        List<SysMessageRecord> sysMessageRecordList = sysMessageRecordService.findList(queryFilter.clear().and("readStatus", 0));
        Set<Long> sysMessageIdSet = new HashSet<>();
        if (Utils.isBlank(sysMessageRecordList)) {
            for (SysMessageRecord sysMessageRecord : sysMessageRecordList) {
                sysMessageIdSet.add(sysMessageRecord.getSysMessageId());
            }
        }


        List<SysMessageRecord> updateSysMessageRecordList = new ArrayList<>();
        if (sysMessageIdSet.size() != 0) {
            // 获取未送达消息
            List<SysMessage> sysMessageList = sysMessageService.findList(queryFilter.clear().and("id", Relation.IN, sysMessageIdSet.toArray()));
            Map<Long, SysMessage> sysMessageMapping = new HashMap<>();
            if (Utils.isBlank(sysMessageList)) {
                for (SysMessage sysMessage : sysMessageList) {
                    sysMessageMapping.put(sysMessage.getId(), sysMessage);
                }
            }

            // 发送消息
            if (Utils.isBlank(sysMessageRecordList)) {
                for (SysMessageRecord sysMessageRecord : sysMessageRecordList) {
                    int mailReadStatus = sysMessageRecord.getMailReadStatus();
                    int readStatus = sysMessageRecord.getReadStatus();
                    SysMessage sysMessage = sysMessageMapping.get(sysMessageRecord.getSysMessageId());
                    sysMessageService.sendSysMessage(sysMessage, sysMessageRecord);
                    if (!sysMessageRecord.getMailReadStatus().equals(mailReadStatus) || !sysMessageRecord.getReadStatus().equals(readStatus)) {
                        updateSysMessageRecordList.add(sysMessageRecord);
                    }
                }
            }
        }

        // 修改发送成功的用户
        sysMessageRecordService.update(updateSysMessageRecordList);
    }

}
